package com.mresources.common.utils;

import com.mresources.common.dto.bo.UploadFileBo;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

public class FileUtils {

    private FileUtils() {
    }

    public static void createFile(String filePath, UploadFileBo fileBo) {
        try {
            RandomAccessFile randomFile = new RandomAccessFile(filePath, "rw");
            randomFile.setLength(fileBo.getTotalSize());
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeFile(String filePath, UploadFileBo fileBo, InputStream inputStream) {
        try {
            RandomAccessFile randomFile = new RandomAccessFile(filePath, "rw");
            byte[] byteBuffer = new byte[fileBo.getCurrentChunkSize()];
            int byteCount;
            int writeCont = 0;
            long pos = (long) (fileBo.getChunkNumber() - 1) * fileBo.getChunkSize();
            randomFile.seek(pos);
            while ((byteCount = inputStream.read(byteBuffer)) != -1) {
                randomFile.write(byteBuffer, writeCont, byteCount);
                writeCont += byteCount;
            }
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
